package org.rslai.autotest.core.page.impl;

import org.apache.commons.lang3.Validate;
import org.rslai.autotest.core.page.SpringContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

/**
 * 保存 Spring ApplicationContext，可在需要的时候候取出 ApplicaitonContext 或 bean
 * @author rslai
 */
public class SpringContextImpl implements SpringContext {
	private ApplicationContext applicationContext = null;

	/**
	 * 实现ApplicationContextAware接口, 注入Context
	 */
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

	/**
	 * 实现DisposableBean接口, 在Context关闭时清理静态变量.
	 */
	@Override
	public void destroy() throws Exception {
		this.clearHolder();
	}

	@Override
	public ApplicationContext getApplicationContext() {
		assertContextInjected();
		return applicationContext;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T getBean(String name) {
		assertContextInjected();
		return (T) applicationContext.getBean(name);
	}

	@Override
	public <T> T getBean(Class<T> requiredType) {
		assertContextInjected();
		return applicationContext.getBean(requiredType);
	}

	@Override
	public void clearHolder() {
		applicationContext = null;
	}

	/**
	 * 检查ApplicationContext不为空.
	 */
	private void assertContextInjected() {
		Validate.validState(applicationContext != null, "applicaitonContext属性未注入, 请在applicationContext中定义SpringContextHolder。");
	}

}